package com.langsin.LinkedListDemo;

/**
 * @Auther: MFM
 * @Date: 2021/7/21 - 07 - 21 - 20:35
 * @version: 1.0
 */

public class LinkedListQueue<E> implements Queue<E> {

    //内部类
    private class Node {
        public E e;
        public Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }

        public Node(E e) {
            this(e, null);
        }

        public Node() {
            this(null, null);
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    //头节点
    private Node head;
    //尾节点
    private Node tail;

    private int size;

    public LinkedListQueue() {
        head = null;
        tail = null;
        size = 0;
    }


    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }


    //链表头 添加删除简单
    //链表尾 添加简单 删除麻烦
    //入队 链表尾
    //初度 链表头
    @Override
    public void enQueue(E e) {

        if (tail == null) {
            tail = new Node(e);
            head = tail;
        } else {

            //生成一个元素e的节点，并且把它放到当前为tail的尾节点之后
            tail.next = new Node(e);
            //让新添加的节点成为tail的尾节点
            tail = tail.next;
        }

        size++;
    }

    @Override
    public E deQueue() {

        if (isEmpty()) {
            throw new IllegalArgumentException("无法从空队列中执行出队操作");
        }

        Node retNode = head;
        head = head.next;
        retNode.next = null;
        size--;

        return retNode.e;
    }

    @Override
    public E getFront() {

        if (isEmpty()) {
            throw new IllegalArgumentException("队列为空");
        }


        return head.e;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append("Queue：队首");
        Node current = head;
        while (current != null) {
            res.append(current + "->");
            current = current.next;
        }
        res.append("队尾");
        return res.toString();
    }


}
